package cn.samler.diandi.api.Interceptor;


import cn.samler.diandi.api.annotation.IgnoreTokenCheck;
import cn.samler.diandi.api.entity.User;
import cn.samler.diandi.api.mapper.UserMapper;
import cn.samler.diandi.api.model.io.Response;
import cn.samler.diandi.api.utils.JWTUtil;
import cn.samler.diandi.api.utils.ResponseBuilder;
import cn.samler.diandi.api.utils.UserUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    private final UserMapper userMapper;
    private final JWTUtil jwtUtil;

    JWTInterceptor(UserMapper userMapper, JWTUtil jwtUtil) {
        this.userMapper = userMapper;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("access_token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod))
            return true;

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 检查是否需要进行jwt拦截检测
        if (!method.isAnnotationPresent(IgnoreTokenCheck.class)) {
            DecodedJWT jwtObj = (token != null && Pattern.matches("[\\w-]+\\.[\\w-]+\\.[\\w-]+", token)) ? jwtUtil.verify(token) : null;
            if (jwtObj != null) {
                JSONObject json = jwtUtil.getPayload(jwtObj);
                Integer uid = (Integer) (json.getOrDefault("uid", null));
                if (uid != null) {
                    User user = userMapper.findById(uid);

                    //验证是否修改过密码
                    if (user != null && jwtUtil.isAvailable(jwtObj, "token", UserUtil.getToken(user))) {
                        //如果需要重新创建一个token 则通知客户端保存新的toekn 并且将新的token返回
                        if (jwtUtil.isNeedRefresh(jwtObj)) {
                            Response resp = new ResponseBuilder()
                                    .tokenRefreshed(UserUtil.getAccessToken(user))
                                    .msg("access token refreshed")
                                    .build();

                            result(response, resp);
                            return false;
                        }

                        request.setAttribute("current_user", user);
                        return true;
                    }
                }
            }

            //验证未通过
            result(response, new ResponseBuilder().tokenInvalid().msg("access token invalid").build());
            return false;
        }

        return true;
    }

    private void result(HttpServletResponse response, Response result) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(200);
        try (PrintWriter out = response.getWriter()){
            ObjectMapper objectMapper = new ObjectMapper();
            out.append(objectMapper.writeValueAsString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
